﻿using System;
using System.Collections.Generic;

using Autofac;
using Autofac.Extensions.DependencyInjection;

using Dotnet3WebApiDemo.Services;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace Dotnet3WebApiDemo.Controllers
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class IOCTestController : ControllerBase
    {
        public ISingletonService SingletonService1 { get; set; } = null!;
        public ISingletonService SingletonService2 { get; set; } = null!;

        public IScopedService ScopedService1 { get; set; } = null!;
        public IScopedService ScopedService2 { get; set; } = null!;

        public ITransientService TransientService1 { get; set; } = null!;
        public ITransientService TransientService2 { get; set; } = null!;

        [HttpGet]
        public Dictionary<string, string> Get()
        {
            Dictionary<string, string> datas = new Dictionary<string, string>
            {
                [nameof(SingletonService1)] = SingletonService1.ToString()!,
                [nameof(SingletonService2)] = SingletonService2.ToString()!,

                [nameof(ScopedService1)] = ScopedService1.ToString()!,
                [nameof(ScopedService2)] = ScopedService2.ToString()!,

                [nameof(TransientService1)] = TransientService1.ToString()!,
                [nameof(TransientService2)] = TransientService2.ToString()!,
            };
            return datas;
        }

        public IServiceProvider ServiceProvider { get; set; }

        [HttpGet]
        public Dictionary<string, string> GetPerRequestService()
        {
            AutofacServiceProvider autofacServiceProvider = ServiceProvider as AutofacServiceProvider;
            using var transactionScope = autofacServiceProvider.LifetimeScope.BeginLifetimeScope("transaction");
            using var scope = transactionScope.BeginLifetimeScope();
            using var scope2 = transactionScope.BeginLifetimeScope();

            IPerRequestService perRequestService = scope.Resolve<IPerRequestService>();
            IPerRequestService perRequestService2 = scope.Resolve<IPerRequestService>();

            Dictionary<string, string> datas = new Dictionary<string, string>
            {
                [nameof(perRequestService)] = perRequestService.ToString()!,
                [nameof(perRequestService2)] = perRequestService2.ToString()!,
            };

            return datas;
        }
    }
}
